package demo20;

import java.util.ArrayList;
import java.util.List;

/**
 * 组合总和
 * https://leetcode.cn/problems/Ygoe9J/submissions/568431607/
 */
class Solution {
    List<List<Integer>> ret;
    List<Integer> path;
    int sum = 0;
    int t;
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        ret = new ArrayList<>();
        path = new ArrayList<>();
        t = target;
        dfs(candidates, 0,0);
        return ret;
    }

    private void dfs(int[] candidates, int index,int sum) {
        if(sum == t ) {
            ret.add(new ArrayList<>(path));
            return;
        }
        if(sum > t) return;
        for(int i = index; i < candidates.length ; i++) {
            path.add(candidates[i]);
            dfs(candidates, i, sum + candidates[i]);
            path.remove(path.size() - 1);
        }
    }
}
class Demo {
    public static void main(String[] args) {
        Solution solution = new Solution();
        List<List<Integer>> lists = solution.combinationSum(new int[]{2,3,5}, 8);
        for(List<Integer> list:lists) {
            System.out.println(list);
        }
    }
}